package register

import (
	"fmt"
	"github.com/hashicorp/consul/api"
)

type Registry struct {
	HOST string
	Port int
}

type RegistryClient interface {
	Register(address string,port int,name string,id string)error
	DeRegister(serviceId string)error
}


func NewRegistryClient(host string,port int )RegistryClient{
	return &Registry{
		HOST: host,
		Port: port,
	}
}

func (r *Registry)DeRegister(serviceId string)error{
	cfg :=api.DefaultConfig()
	cfg.Address = fmt.Sprintf("%s:%d",r.HOST,r.Port)
	client,err :=api.NewClient(cfg)
	if err != nil {
		panic(err)
	}
	err = client.Agent().ServiceDeregister(serviceId)
	return err
}

func (r *Registry)Register(address string,port int,name string,id string)error{
	cfg :=api.DefaultConfig()
	cfg.Address =fmt.Sprintf("%s:%d",r.HOST,r.Port)
	client,err :=api.NewClient(cfg)
	if err != nil {
		panic(err)
	}
	//生成注册对象
	registration :=new(api.AgentServiceRegistration)
	registration.Name = name
	registration.ID = id
	registration.Port = port
	registration.Tags = []string{"小花生"}
	registration.Address = address

	//生成对应的检查对象
	check :=&api.AgentServiceCheck{
		HTTP: fmt.Sprintf("http://%s:%d/health",address,port),
		Timeout: "5s",
		Interval: "5s",
		DeregisterCriticalServiceAfter: "10s",
	}
	registration.Check = check
	err = client.Agent().ServiceRegister(registration)
	if err != nil {
		panic(err)
	}
	return nil
}
//获取所有的服务
func AllServices(){
	cfg :=api.DefaultConfig()
	cfg.Address = "192.168.178.120:8500"
	client,err :=api.NewClient(cfg)
	if err != nil {
		panic(err)
	}
	data,err :=client.Agent().Services()
	if err != nil {
		panic(err)
	}
	for key,_ :=range data{
		fmt.Println(key)
	}
}
func FilterService(){
	cfg :=api.DefaultConfig()
	cfg.Address = "192.168.178.120:8500"
	client,err :=api.NewClient(cfg)
	if err != nil {
		panic(err)
	}
	data,_ :=client.Agent().ServicesWithFilter(`Service =="user-web"`)
	for key,_:=range data{
		fmt.Println(key)
	}
}

